import dayjs from 'dayjs'
import { appConfig } from '@/config'
import { isFunction } from './plugins'

export const setBaseUrlFile = (str: string) => {
  return str.replaceAll(
    /(!\[.*\]\(|<img src=")(?!http)/g,
    `$1${appConfig.baseUrlFile}`
  )
}

export const removeBaseUrlFile = (str: string) => {
  return str.replaceAll(appConfig.baseUrlFile, '')
}

export const joinBaseUrlFile = (url: string) => {
  if (/^blob:/.test(url)) return url

  return /^https?:\/\//.test(url) ? url : url
  // return /^https?:\/\//.test(url) ? url : appConfig.baseUrlFile + url
}

export const dateFormat = (
  value: dayjs.ConfigType,
  template = 'YYYY-MM-DD HH:mm:ss'
) => {
  try {
    return dayjs(value).format(template)
  } catch {
    const toString = value?.toString
    const res = isFunction(toString) ? toString() : ''
    return res || ''
  }
}

interface ValueFormatConfig {
  separator?: string
  labelKey?: string
  valueKey?: string
}

export const valueFormat = (
  options: any[],
  value: any | any[],
  config?: ValueFormatConfig
) => {
  const {
    separator = ',',
    labelKey = 'label',
    valueKey = 'value'
  } = config || {}

  if (!Array.isArray(value)) {
    value = separator ? `${value}`.split(separator) : [value]
  }

  return value
    .map((val) => options.find((item) => item?.[valueKey] == val)?.[labelKey])
    .filter(Boolean)
    .join(separator || '')
}

function convertSection(section, needZero) {
  const units = ['', '十', '百', '千']
  const chars = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  let str = ''
  let zeroFlag = false
  for (let i = 0; section > 0; i++) {
    const mod = section % 10
    if (mod === 0) {
      if (!zeroFlag) {
        zeroFlag = true
        str = chars[mod] + str
      }
    } else {
      zeroFlag = false
      str = chars[mod] + units[i] + str
    }
    section = Math.floor(section / 10)
  }
  if (needZero && str !== '') {
    str = '零' + str
  }
  return str
}

export function numberFormat(num) {
  const chars = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const sectionUnits = ['', '万', '亿', '万亿']

  if (num === 0) return '零'

  let str = num < 0 ? '负' : ''
  num = Math.abs(num)

  // 处理小数部分
  let decimalPart = ''
  if (String(num).includes('.')) {
    const parts = String(num).split('.')
    num = parseInt(parts[0], 10)
    decimalPart =
      '点' +
      parts[1]
        .split('')
        .map((n) => chars[n])
        .join('')
  }

  let sectionIndex = 0
  while (num > 0) {
    const part = num % 10000
    const partStr = convertSection(part, part !== 0 && sectionIndex > 0)
    str = partStr + (partStr !== '' ? sectionUnits[sectionIndex] : '') + str
    num = Math.floor(num / 10000)
    sectionIndex++
  }

  return str + decimalPart
}

export const htmlToText = (str = '') => {
  return str.replace(/<.*?>|&.*;|\s/g, '')
}
